package com.pay.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pay.order.dao.PayOrderMapper;
import com.pay.order.pojo.PayOrder;
import com.pay.order.pojo.PayRate;
import com.pay.order.service.PayOrderService;
import com.pay.order.service.PayRateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements PayOrderService {
   @Autowired
   private PayOrderMapper payOrderMapper;
   @Autowired
   private PayRateService payRateService;

    @Override
    public void updateStatusById(Integer id, Integer status) {
        payOrderMapper.updateStatusById(id,status);
    }

    @Override
    public Page<PayOrder> queryPageList(PayOrder payOrder, Integer page, Integer limit) {

        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<PayOrder>();
       if(StringUtils.isNotEmpty(payOrder.getCode())) {
           queryWrapper.like("code", payOrder.getCode());
       }
       if(Objects.nonNull(payOrder.getStatus())) {
           queryWrapper.eq("status", payOrder.getStatus());
       }
        queryWrapper.orderByDesc("create_time");
        Page<PayOrder> payOrderPage = payOrderMapper.selectPage(new Page<PayOrder>(page, limit), queryWrapper);
        payOrderPage.getRecords().forEach(l->{
            l.setPayTypeStr(l.getPayType());
            l.setStatusStr(l.getStatus());
        });
        return payOrderPage;
    }

    @Override
    public boolean save(PayOrder payOrder) {
        PayRate payRate = payRateService.getById(payOrder.getRateType());
        payOrder.setRateName(payRate.getName());
        payOrder.setRate(payRate.getRate());
        payOrder.setCode(generateCode());
        payOrder.setStatus(0);
        payOrder.setCreateTime(new Date());
        payOrder.setUpdateTime(payOrder.getCreateTime());
        return payOrderMapper.insert(payOrder)>1;
    }
    /**
     * 生成订单号
     * @return
     */
    public String generateCode(){
        ReentrantLock lock=new ReentrantLock();
        lock.lock();
        try {
            String code="";
            SimpleDateFormat sdf=new SimpleDateFormat("YYYYMMDDHHmmsss");
            code=sdf.format(new Date());
            lock.unlock();
            return code;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
